package fr.web325.servlet.api.cart;

import fr.web325.bean.Book;
import fr.web325.bean.Json;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@WebServlet("/api/removeCart")
public class RemoveCart extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String str = req.getParameter("removeIdList");
        List<String> removeList = Arrays.asList(str.split(","));
        // 获得session对象
        HttpSession session = req.getSession();
        // 从session中获取购物车对象
        Map<Book, Integer> cart = (Map<Book, Integer>)session.getAttribute("cart");
        if(cart == null){
            resp.getWriter().print(new Json(200,null,"购物车为空,请先添加商品到购物车中!").getRespJson());
            return;
        }
        int oldLen = cart.size();
        Iterator<Book> iter = cart.keySet().iterator();

        int y = 0;
        // map对象循环中不能操作remove否则异常
        while (iter.hasNext()) {
            iter.next();
            if(removeList.contains(Integer.toString(y))){
                iter.remove();
            }
            y++;
        }
        session.setAttribute("cart", cart);
        if(cart.size() == oldLen){
            resp.getWriter().print(new Json(202,null,"移出购物车失败!").getRespJson());
        }else{
            resp.getWriter().print(new Json(201,null,"移出购物车成功!").getRespJson());
        }
    }
}
